package com.s10.ecloud.web.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.s10.ecloud.web.dao.ICommandDAO;
import com.s10.ecloud.web.model.Command;
import com.s10.ecloud.web.model.PageModel;

@Repository
public class CommandDAO implements ICommandDAO {

	@Resource
	private SessionFactory sessionFactory;

	@Override
	public void makePageModel(PageModel pageModel, int deviceModelId) {

		String queryCountHql = "select count(*) from Command where deviceModelId=:deviceModelId";
		List datas = new ArrayList();
		long totoalPages = 0;

		Query query = sessionFactory.getCurrentSession().createQuery(queryCountHql);
		query.setParameter("deviceModelId", deviceModelId);

		totoalPages = ((Long) query.uniqueResult()).longValue();

		queryCountHql = "from Command where deviceModelId=:deviceModelId";

		query = sessionFactory.getCurrentSession().createQuery(queryCountHql);
		query.setParameter("deviceModelId", deviceModelId);

		datas = query.setFirstResult(pageModel.getOffset()).setMaxResults(pageModel.getMaxPageItems()).list();

		pageModel.setTotal((int) totoalPages);
		pageModel.setList(datas);

	}

	@Override
	public List<Command> getCommandByDeviceModelId(int deviceModelId) {
		String queryCountHql = "from Command where deviceModelId=:deviceModelId";

		Query query = sessionFactory.getCurrentSession().createQuery(queryCountHql);
		query.setParameter("deviceModelId", deviceModelId);
		List<Command> list = query.list();

		if (list == null) {
			return new ArrayList<Command>();
		}

		return list;
	}

	@Override
	public Command getCommandByCommandId(int commandId) {

		Object o = sessionFactory.getCurrentSession().get(Command.class, commandId);

		if (o != null) {
			return (Command) o;
		} else {
			return null;
		}
	}

	@Override
	public void addCommandByCommandId(Command command) {
		sessionFactory.getCurrentSession().save(command);
	}

	@Override
	public void updateCommandByCommandId(Command command) {
		sessionFactory.getCurrentSession().update(command);

	}

	@Override
	public void deleteCommandByCommandId(int commandId) {
		Object o = this.getCommandByCommandId(commandId);
		sessionFactory.getCurrentSession().delete(o);
	}

}
